from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect
from my_auth.forms import RegisterForm
from django.contrib.auth import authenticate, login,  logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages

# from this tutorial http://codingnstuff.com/2010/01/create-your-user-management-frontend-in-django/
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/")
    else:
        form = RegisterForm()
    return render_to_response("shunt/register.html",  {'form':form},  context_instance=RequestContext(request))

def dologin(request):
    status = "Bitte einloggen"
    username = password = ""
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')
        
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request,  user)
                messages.add_message(request, messages.SUCCESS, 'Erfolgreich eingeloggt.')
                return HttpResponseRedirect("/")
            else:
                messages.add_message(request, messages.INFO, 'Dein Account ist noch nicht aktiviert')
        else:
            messages.add_message(request, messages.WARNING, 'Dein Benutzername/Passwort ist nicht korrekt')
    else:
        form = AuthenticationForm(request)
    return render_to_response("shunt/login.html",  {'form': form},  context_instance=RequestContext(request))
    
def dologout(request):
    if request.user.is_authenticated:
        logout(request)
        return HttpResponseRedirect("/")
    else:
        return HttpResponseRedirect("/user/login")
